package com.turing.usdtpay.mvp.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.turing.usdtpay.R;
import com.turing.usdtpay.base.BaseFragment;
import com.turing.usdtpay.entity.PayChannelData;
import com.turing.usdtpay.entity.RobSettingData;
import com.turing.usdtpay.entity.UserSettingData;
import com.turing.usdtpay.mvp.contract.SettingRobContract;
import com.turing.usdtpay.mvp.presenter.SettingRobPresent;
import com.turing.usdtpay.mvp.view.BaseTitleView;
import com.turing.usdtpay.utils.FormatUtils;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.ToastUtils;

import java.util.List;

/**
 * @作者：JAY
 * @创建时间：2019/10/10 18:15
 * @描述：
 **/
public class RobSettingFragment extends BaseFragment implements SettingRobContract.View {

    private EditText mBuyMin, mBuyMax, mSellMin, mSellMax;
    private TextView mBuyPrice, mBuyCount, mSellPrice, mSellCount;
    private Button mBuy, mSell;
    private ImageView mAlipay, mWechat;
    private SettingRobContract.Present mPresent;
    private double mRate = 6.88;
    private int mBankMin = 20000, mBankMax = 200000, mWechatMin = 0, mWechatMax = 999999, mAliPayMin = 0, mAliPayMax = 999999;
    private boolean isBuy, isSellAlipay, isSellWechat;
    private int mPayType = 1;
    private int can_use_Money = 0;
    private ProgressBar mProgress;

    public static RobSettingFragment newInstance(Bundle bundle) {
        RobSettingFragment fragment = new RobSettingFragment();
        if (bundle != null) {
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setPresenter(new SettingRobPresent(this));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        initView(view);
        initTitle();
        initData();
        return view;
    }

    private void initData() {
        try {
            Double max = Double.valueOf(mBuyMax.getText().toString());
            double count = (max / mRate);
            mBuyCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Double max2 = Double.valueOf(mSellMax.getText().toString());
            double count2 = (max2 / mRate);
            mSellCount.setText(FormatUtils.NoumberFromat8(count2) + " USDT");
        } catch (Exception e) {
            e.printStackTrace();
        }
        mPresent.getSettingInfo(getActivity());
    }

    private void initTitle() {
        setTitle("设置");
    }

    private void initView(View view) {
        mBuyMin = (EditText) view.findViewById(R.id.et_buy_min);
        mBuyMax = (EditText) view.findViewById(R.id.et_buy_max);
        mSellMin = (EditText) view.findViewById(R.id.et_sell_min);
        mSellMax = (EditText) view.findViewById(R.id.et_sell_max);
        mBuyCount = (TextView) view.findViewById(R.id.tv_buy_count);
        mBuyPrice = (TextView) view.findViewById(R.id.tv_buy_price);
        mSellCount = (TextView) view.findViewById(R.id.tv_sell_count);
        mSellPrice = (TextView) view.findViewById(R.id.tv_sell_price);
        mAlipay = (ImageView) view.findViewById(R.id.iv_alipay);
        mWechat = (ImageView) view.findViewById(R.id.iv_wechat);

        mBuy = (Button) view.findViewById(R.id.btn_buy_save);
        mSell = (Button) view.findViewById(R.id.btn_sell_save);
        mProgress = (ProgressBar) view.findViewById(R.id.progress);

        mBuy.setOnClickListener(this);
        mSell.setOnClickListener(this);
        mAlipay.setOnClickListener(this);
        mWechat.setOnClickListener(this);
        mBuyMax.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String result = s.toString();
                try {
                    Double max = Double.valueOf(result);
                    LogUtils.d("最大 --》" + max);
                    double count = (max / mRate);
                    mBuyCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mSellMax.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String result = s.toString();
                try {
                    Double max = Double.valueOf(result);
                    LogUtils.d("最大 --》" + max);
                    double count = (max / mRate);
                    mSellCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == mBuy.getId()) {
            if (TextUtils.isEmpty(mBuyMin.getText().toString()) && TextUtils.isEmpty(mBuyMax.getText().toString())) {
                ToastUtils.showToast(getActivity(), "最低和最高金额不能为空");
                return;
            }
            LogUtils.d("min ->" + mBankMin + "max ->" + mBankMax);
            try {
                double min = Double.valueOf(mBuyMin.getText().toString()) * 100;
                double max = Double.valueOf(mBuyMax.getText().toString()) * 100;
                if (min < mBankMin || max > mBankMax) {
                    ToastUtils.showNormolToast(getActivity(), "最低金额不低于" + mBankMin / 100 + ",最高金额不超过" + mBankMax / 100);
                    return;
                }
                if (min > max) {
                    ToastUtils.showNormolToast(getActivity(), "最高金额要大于最小金额");
                    return;
                }
                int min1 = (int) min;
                int max1 = (int) max;
                if (isBuy) {
                    mProgress.setVisibility(View.VISIBLE);
                    mPresent.setBuyInfo(getActivity(), min1, max1, "1");
                } else {
                    ToastUtils.showNormolToast(getActivity(), "不可购买");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        } else if (v.getId() == mSell.getId()) {

            if (TextUtils.isEmpty(mSellMin.getText().toString()) && TextUtils.isEmpty(mSellMax.getText().toString())) {
                ToastUtils.showToast(getActivity(), "最低和最高金额不能为空");
                return;
            }

            try {
                if (mPayType == 1) {
                    LogUtils.d("min ->" + mAliPayMin + "max ->" + mAliPayMax);
                    double min = Double.valueOf(mSellMin.getText().toString()) * 100;
                    double max = Double.valueOf(mSellMax.getText().toString()) * 100;
                    if (min < mAliPayMin || max > mAliPayMax) {
                        ToastUtils.showNormolToast(getActivity(), "最低金额不低于" + mAliPayMin / 100 + ",最高金额不超过" + mAliPayMax / 100);
                        return;
                    }
                    if (min > max) {
                        ToastUtils.showNormolToast(getActivity(), "最高金额要大于最小金额");
                        return;
                    }
                    int min1 = (int) min;
                    int max1 = (int) max;
                    if (max1 > can_use_Money) {
                        ToastUtils.showNormolToast(getActivity(), "您的可用金额为 :" + can_use_Money / 100);
                        return;
                    }
                    LogUtils.d("保存支付宝");
                    if (isSellAlipay) {
                        mProgress.setVisibility(View.VISIBLE);
                        mPresent.setSellInfo(getActivity(), min1, max1, "3");
                    } else {
                        ToastUtils.showNormolToast(getActivity(), "不可出售");
                    }

                } else {
                    LogUtils.d("min ->" + mWechatMin + "max ->" + mWechatMax);
                    double min = Double.valueOf(mSellMin.getText().toString()) * 100;
                    double max = Double.valueOf(mSellMax.getText().toString()) * 100;
                    if (min < mWechatMin || max > mWechatMax) {
                        ToastUtils.showNormolToast(getActivity(), "最低金额不低于" + mWechatMin / 100 + ",最高金额不超过" + mWechatMax / 100);
                        return;
                    }
                    if (min > max) {
                        ToastUtils.showNormolToast(getActivity(), "最高金额要大于最小金额");
                        return;
                    }
                    int min1 = (int) min;
                    int max1 = (int) max;
                    if (max1 > can_use_Money) {
                        ToastUtils.showNormolToast(getActivity(), "您的可用金额为 :" + can_use_Money / 100);
                        return;
                    }
                    if (isSellWechat) {
                        mProgress.setVisibility(View.VISIBLE);
                        LogUtils.d("保存微信");
                        mPresent.setSellInfo(getActivity(), min1, max1, "2");
                    } else {
                        ToastUtils.showNormolToast(getActivity(), "不可出售");
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (v.getId() == mAlipay.getId()) {
            mAlipay.setImageResource(R.mipmap.icon_pay_02);
            mWechat.setImageResource(R.mipmap.icon_pay_03_uncheck);
            mPayType = 1;
        } else if (v.getId() == mWechat.getId()) {
            mAlipay.setImageResource(R.mipmap.icon_pay_02_uncheck);
            mWechat.setImageResource(R.mipmap.icon_pay_03);
            mPayType = 2;
        }
    }

    @Override
    public void getBuyInfo() {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(getActivity(), "保存成功");
    }

    @Override
    public void getSellInfo() {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(getActivity(), "保存成功");
    }

    @Override
    public void onFail(String error) {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(getActivity(), error);
    }

    @Override
    public void onSuccess(RobSettingData data) {
        mRate = (double) data.getMoney_change_usdt() / 100;
        mBuyPrice.setText((float) mRate + "");
        mSellPrice.setText((float) mRate + "");
        List<UserSettingData> set_info = data.getSet_info();
        String buy_limit = data.getBuy_money_limit();
        List<PayChannelData> pay_channel = data.getPay_channel();
        can_use_Money = data.getCan_use_money();
        //获取默认最大最小值
        if (data.getSet_pay_channel().size() == 0) {
            String[] split = data.getSell_money_limit().split("\\|");
            mWechatMin = Integer.valueOf(split[0]);
            mWechatMax = Integer.valueOf(split[1]);
            mAliPayMin = Integer.valueOf(split[0]);
            mAliPayMax = Integer.valueOf(split[1]);
        }
        String[] split1 = buy_limit.split("\\|");
        mBankMin = Integer.valueOf(split1[0]);
        mBankMax = Integer.valueOf(split1[1]);
        //设置是否可买卖
        for (PayChannelData channelData : pay_channel) {
            if (channelData.getId() == 1) {
                if (channelData.getIs_buy() == 0) {
                    isBuy = false;
                } else {
                    isBuy = true;
                }
            }else if (channelData.getId() == 2){
                if (channelData.getIs_sell() == 0) {
                    isSellWechat = false;
                } else {
                    isSellWechat = true;
                }
            }else if (channelData.getId() == 3){
                if (channelData.getIs_sell() == 0) {
                    isSellAlipay = false;
                } else {
                    isSellAlipay = true;
                }
            }
        }
        //获取用户设置的最大最小值
        if (set_info.size()>0){
            if (pay_channel != null) {
                for (PayChannelData channelData : pay_channel) {
                    if (channelData.getId() == 1) {
                        String[] split = buy_limit.split("\\|");
                        mBankMin = Integer.valueOf(split[0]);
                        mBankMax = Integer.valueOf(split[1]);
                    } else if (channelData.getId() == 2) {
                        String[] split = channelData.getSell_limit().split("\\|");
                        mWechatMin = Integer.valueOf(split[0]);
                        mWechatMax = Integer.valueOf(split[1]);
                    } else if (channelData.getId() == 3) {
                        String[] split = channelData.getSell_limit().split("\\|");
                        mAliPayMin = Integer.valueOf(split[0]);
                        mAliPayMax = Integer.valueOf(split[1]);
                    }
                }
            }
        }

        //抢买抢卖默认值
        String[] split = data.getBuy_money_limit().split("\\|");
        mBuyMin.setText(Integer.valueOf(split[0])/100+"");
        mBuyMax.setText(Integer.valueOf(split[1])/100+"");
        mBuyMin.setEnabled(false);
        try {
            double count = (((double) Integer.valueOf(split[1])/100) / mRate);
            mBuyCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String[] split2 = data.getSell_money_limit().split("\\|");
        mSellMin.setText(Integer.valueOf(split2[0])/100+"");
        mSellMax.setText(Integer.valueOf(split2[1])/100+"");
        mSellMin.setEnabled(false);

        if (set_info != null) {
            for (int i = 0; i < set_info.size(); i++) {
                UserSettingData settingData = set_info.get(i);
                if ("1".equals(settingData.getPay_channel())){
                    //用户抢买设定值
                    mBuyMax.setText((settingData.getMax_money() / 100) + "");
                    try {
                        double count = (((double) settingData.getMax_money() / 100) / mRate);
                        mBuyCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //用户抢卖设定值（微信）
                if ("2".equals(settingData.getPay_channel())) {
                    mSellMax.setText((settingData.getMax_money() / 100) + "");
                    try {
                        double count = (((double) settingData.getMax_money() / 100) / mRate);
                        mSellCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mAlipay.setImageResource(R.mipmap.icon_pay_02_uncheck);
                    mWechat.setImageResource(R.mipmap.icon_pay_03);
                    mPayType = 2;
                }
                //用户抢卖设定值（支付宝）
                if ("3".equals(settingData.getPay_channel())) {
                    mSellMax.setText((settingData.getMax_money() / 100) + "");
                    try {
                        double count = (((double) settingData.getMax_money() / 100) / mRate);
                        mSellCount.setText(FormatUtils.NoumberFromat8(count) + " USDT");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mAlipay.setImageResource(R.mipmap.icon_pay_02);
                    mWechat.setImageResource(R.mipmap.icon_pay_03_uncheck);
                    mPayType = 1;
                }
            }
        }
    }

    @Override
    public void setPresenter(SettingRobContract.Present presenter) {
        mPresent = presenter;
    }
}
